import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { getHealthInfo, type HealthInfo } from '../../api/outpatient'
import './index.css'

function HealthInfoPage() {
  const navigate = useNavigate()
  
  const [healthInfos, setHealthInfos] = useState<HealthInfo[]>([])
  const [loading, setLoading] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [searchKeyword, setSearchKeyword] = useState('')
  
  const pageSize = 10 // 每页显示10篇文章

  // 加载健康资讯数据
  const loadHealthInfo = async (page: number = 1, keyword: string = '') => {
    setLoading(true)
    try {
      const allData = await getHealthInfo()
      
      // 搜索过滤
      let filteredData = allData
      if (keyword && keyword.trim()) {
        filteredData = allData.filter(info => 
          info.title.toLowerCase().includes(keyword.toLowerCase()) ||
          (info.summary && info.summary.toLowerCase().includes(keyword.toLowerCase())) ||
          info.tag.toLowerCase().includes(keyword.toLowerCase())
        )
      }
      
      // 分页处理
      const startIndex = (page - 1) * pageSize
      const endIndex = startIndex + pageSize
      const pageData = filteredData.slice(startIndex, endIndex)
      
      if (page === 1) {
        setHealthInfos(pageData)
      } else {
        setHealthInfos(prev => [...prev, ...pageData])
      }
      
      setHasMore(endIndex < filteredData.length)
    } catch (error) {
      console.error('加载健康资讯失败:', error)
    } finally {
      setLoading(false)
    }
  }

  // 初始化数据
  useEffect(() => {
    loadHealthInfo(1, '')
  }, [])

  // 处理搜索
  const handleSearch = () => {
    setCurrentPage(1)
    loadHealthInfo(1, searchKeyword)
  }

  // 加载更多
  const loadMore = () => {
    if (!loading && hasMore) {
      const nextPage = currentPage + 1
      setCurrentPage(nextPage)
      loadHealthInfo(nextPage, searchKeyword)
    }
  }

  // 处理文章点击
  const handleArticleClick = (article: HealthInfo) => {
    console.log('点击文章:', article.title)
    // 跳转到文章详情页面
    navigate(`/health-info-detail/${article.id}`)
  }

  // 格式化时间
  const formatTime = (timeStr: string) => {
    const date = new Date(timeStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }

  return (
    <div style={{ minHeight: '100vh', background: '#f5f5f5' }}>
      {/* 顶部导航 */}
      <div style={{ 
        background: '#fff', 
        padding: '12px 16px', 
        borderBottom: '1px solid #eee',
        position: 'sticky',
        top: 0,
        zIndex: 100
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <button 
              onClick={() => navigate(-1)}
              style={{ 
                border: 'none', 
                background: 'none', 
                fontSize: 18, 
                marginRight: 12,
                cursor: 'pointer'
              }}
            >
              ←
            </button>
            <h1 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>
              健康资讯
            </h1>
          </div>
        </div>
        
        {/* 搜索框 */}
        <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
          <input
            type="text"
            placeholder="搜索健康资讯..."
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            style={{
              flex: 1,
              padding: '8px 12px',
              border: '1px solid #ddd',
              borderRadius: 8,
              fontSize: 14
            }}
          />
          <button
            onClick={handleSearch}
            style={{
              padding: '8px 16px',
              background: '#1677ff',
              color: '#fff',
              border: 'none',
              borderRadius: 8,
              cursor: 'pointer'
            }}
          >
            搜索
          </button>
        </div>
      </div>

      {/* 文章列表 */}
      <div style={{ padding: '16px' }}>
        {healthInfos.map((article) => (
          <div 
            key={article.id} 
            style={{ 
              background: '#fff',
              borderRadius: 12,
              padding: 16,
              marginBottom: 12,
              cursor: 'pointer',
              transition: 'all 0.2s ease',
              boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
            }}
            onClick={() => handleArticleClick(article)}
            onMouseEnter={(e) => {
              e.currentTarget.style.transform = 'translateY(-1px)'
              e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.12)'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.transform = 'translateY(0)'
              e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.06)'
            }}
          >
            <div style={{ display: 'flex', gap: 12 }}>
              {/* 文章内容 */}
              <div style={{ flex: 1 }}>
                <h3 style={{ 
                  margin: '0 0 8px 0', 
                  fontSize: 16, 
                  fontWeight: 600,
                  lineHeight: 1.4,
                  color: '#333'
                }}>
                  {article.title}
                </h3>
                
                {article.summary && (
                  <p style={{ 
                    margin: '0 0 8px 0', 
                    fontSize: 14, 
                    color: '#666',
                    lineHeight: 1.5,
                    display: '-webkit-box',
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: 'vertical',
                    overflow: 'hidden'
                  }}>
                    {article.summary}
                  </p>
                )}
                
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <span style={{ 
                      fontSize: 12, 
                      color: '#6b7aff',
                      background: '#f0f2ff',
                      padding: '2px 8px',
                      borderRadius: 4
                    }}>
                      {article.tag}
                    </span>
                    {article.publishTime && (
                      <span style={{ fontSize: 12, color: '#999' }}>
                        {formatTime(article.publishTime)}
                      </span>
                    )}
                  </div>
                  
                  <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 12, color: '#8390a3' }}>
                    <span>👍 {article.likes}</span>
                    <span>👁️ {article.views}</span>
                  </div>
                </div>
              </div>
              
              {/* 文章封面 */}
              <img 
                src={article.cover} 
                alt={article.title}
                style={{ 
                  width: 80, 
                  height: 80, 
                  borderRadius: 8, 
                  objectFit: 'cover',
                  flexShrink: 0
                }}
              />
            </div>
          </div>
        ))}

        {/* 加载更多按钮 */}
        {hasMore && (
          <div style={{ textAlign: 'center', marginTop: 20 }}>
            <button
              onClick={loadMore}
              disabled={loading}
              style={{
                padding: '12px 24px',
                background: loading ? '#ccc' : '#1677ff',
                color: '#fff',
                border: 'none',
                borderRadius: 8,
                cursor: loading ? 'not-allowed' : 'pointer',
                fontSize: 14
              }}
            >
              {loading ? '加载中...' : '加载更多'}
            </button>
          </div>
        )}

        {/* 没有更多数据提示 */}
        {!hasMore && healthInfos.length > 0 && (
          <div style={{ 
            textAlign: 'center', 
            color: '#999', 
            fontSize: 14,
            marginTop: 20
          }}>
            没有更多数据了
          </div>
        )}

        {/* 空状态 */}
        {!loading && healthInfos.length === 0 && (
          <div style={{ 
            textAlign: 'center', 
            padding: '40px 20px',
            color: '#999'
          }}>
            <div style={{ fontSize: 48, marginBottom: 16 }}>📰</div>
            <div style={{ fontSize: 16, marginBottom: 8 }}>暂无相关资讯</div>
            <div style={{ fontSize: 14 }}>试试其他关键词搜索</div>
          </div>
        )}
      </div>
    </div>
  )
}

export default HealthInfoPage
